package com.ljc.template;

import com.ljc.common.templates.DirectiveHandler;
import com.ljc.common.templates.TemplateDirective;
import com.ljc.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 本周热议模板模型
 *
 * @Author: ljc
 * @Date:Created in 22:33 2021/12/7
 */
@Component
public class HotsTemplate extends TemplateDirective {
    @Autowired
    RedisUtil redisUtil;

    @Override
    public String getName() {
        return "hots";
    }

    @Override
    public void execute(DirectiveHandler handler) throws Exception {
        String weekRankkey = "week:rank";
        Set<ZSetOperations.TypedTuple> zSetRank = redisUtil.getZSetRank(weekRankkey, 0, 6);
        List<Map> hotPosts = new ArrayList<Map>();
        for (ZSetOperations.TypedTuple typedTuple : zSetRank) {
            Map<String, Object> map = new HashMap<>();
            Object value = typedTuple.getValue();//post的id
            String postKey = "rank:post:" + value;
            map.put("id", value);
            map.put("title", redisUtil.hget(postKey, "post:title"));
            map.put("commentCount", typedTuple.getScore());
            hotPosts.add(map);
        }
        handler.put(RESULTS,hotPosts).render();
    }

}
